package com.zhny.aiot.control.cabinet.plugin.factory.imp;

import com.zhny.aiot.control.cabinet.plugin.ControlCabinetConst;
import com.zhny.aiot.control.cabinet.plugin.factory.IControlCabinetFactory;
import com.zhny.aiot.control.cabinet.plugin.model.ControlCabinetStoreEntry;
import com.zhny.aiot.plugin.modbus.device.ModemDevice;
import com.zhny.aiot.plugin.modbus.handler.model.ModemResponseMessage;
import io.netty.buffer.ByteBuf;

public class WriteFactoryImpl implements IControlCabinetFactory {
    @Override
    public int getCode() {
        return ControlCabinetConst.WRITE;
    }

    @Override
    public ControlCabinetStoreEntry getStoreEntry(ModemResponseMessage modemResponseMessage, ModemDevice device) {
        int code = modemResponseMessage.getFunction();
        ByteBuf buf = modemResponseMessage.getData();
        int len = modemResponseMessage.getSize();
        if(code == getCode()){
            ControlCabinetStoreEntry storeEntry = onDecode(buf,len);
            if(storeEntry != null)
                device.saveReal(storeEntry);
            return storeEntry;
        }
        return null;
    }

    private ControlCabinetStoreEntry onDecode(ByteBuf buf,int len){
        ControlCabinetStoreEntry storeEntry = new ControlCabinetStoreEntry();
        Integer value = buf.readUnsignedShort();
        buf.release();
        if(len == 20){
            storeEntry.setAdValve1status(value*1.0f);
            return storeEntry;
        }
        else if(len == 22){
            storeEntry.setAdValve2status(value*1.0f);
            return storeEntry;
        }
        return null;
    }
}
